package com.jy.unkown.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jiayou.ziyou_ad.utils.MD5Util;
import com.jy.common.BaseApplication;
import com.jy.unkown.AdCallBack;
import com.jy.unkown.DownloadUtil;
import com.jy.unkown.InstallObsever;
import com.jy.unkown.MultiDownloadHelper;
import com.jy.unkown.OkHttpUtil;
import com.jy.unkown.UNKOWN;
import com.jy.unkown.WebActivty;
import com.jy.unkown.entity.UnkownAdBean;
import com.jy.unkown.inter.aa.IADTick;
import com.jy.unkown.inter.aa.IClick;
import com.jy.unkown.inter.aa.IClose;
import com.jy.unkown.inter.aa.IExposure;
import com.jy.unkown.inter.aa.IReward;
import com.jy.unkown.inter.aa.ISkip;
import com.jy.utils.cache.SpManager;
import com.jy.utils.cache.k;
import com.jy.utils.call.CallBack;
import com.jy.utils.utils.ApkUtils;
import com.jy.utils.utils.LogUtils;
import com.jy.utils.utils.UI;

import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

public abstract class UnkownADView extends FrameLayout implements View.OnClickListener, InstallObsever.InstallCallBack {

    AdCallBack adCallBack;

    public static String TAG = "UnkownADView";

    public void setTAG(String TAG) {
        this.TAG = TAG;
    }

    public void setAdCallBack(AdCallBack adCallBack) {
        this.adCallBack = adCallBack;
    }

    public UnkownADView(@NonNull Context context) {
        super(context);
    }

    public UnkownADView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public UnkownADView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    UnkownAdBean baseUnkownAd;

    public void setUnkownAd(UnkownAdBean baseUnkownAd) {
        this.baseUnkownAd = baseUnkownAd;
    }


    protected UnkownAdBean.MetaGroupDTO getMetaGroupDTOBean() {
        if (baseUnkownAd == null) {
            return null;
        }
        UnkownAdBean unkownAdBean = baseUnkownAd;
        if (unkownAdBean.metaGroup != null && unkownAdBean.metaGroup.size() > 0) {
            UnkownAdBean.MetaGroupDTO metaGroupDTO = unkownAdBean.metaGroup.get(0);
            return metaGroupDTO;
        }
        return null;
    }


//    private static class InstallCallBackProxy implements InstallObsever.InstallCallBack {
//        UnkownAdBean.MetaGroupDTO metaGroupDTO;
//        WeakReference<UnkownADView> unkownADViewWeakReference;
//
//
//        public InstallCallBackProxy(UnkownAdBean.MetaGroupDTO metaGroupDTO, UnkownADView unkownADView) {
//            this.metaGroupDTO = metaGroupDTO;
//            unkownADViewWeakReference = new WeakReference<>(unkownADView);
//        }
//
//        @Override
//        public void installSucc() {
//            if (unkownADViewWeakReference.get() != null) {
//                unkownADViewWeakReference.get().openApp(metaGroupDTO);
//            }
//        }
//    }


    //    InstallObsever.InstallCallBack installCallBack = new InstallObsever.InstallCallBack() {
//        @Override
//        public void installSucc() {
//            UnkownAdBean.MetaGroupDTO metaGroupDTO = getMetaGroupDTOBean();
//            openApp(metaGroupDTO);
//        }
//    };
    @Override
    public void installSucc() {
//        UnkownAdBean.MetaGroupDTO metaGroupDTO = getMetaGroupDTOBean();
//        openApp(metaGroupDTO);
    }

    boolean videoMute;
    public void setVideoMute(boolean videoMute) {
        this.videoMute=videoMute;
    }


    public static class ProxyDownListener implements NotifyDownloadListener {
        SoftReference<UnkownADView> unkownADViewSoftReference;

        public ProxyDownListener(UnkownADView unkownADView) {
            unkownADViewSoftReference = new SoftReference<>(unkownADView);
        }

        @Override
        public void download(String url) {
            UnkownADView unkownADView = unkownADViewSoftReference.get();
            if (unkownADView != null) {
                UnkownAdBean.MetaGroupDTO metaGroupDTO = unkownADView.getMetaGroupDTOBean();
                String fileName = MD5Util.getMD5(metaGroupDTO.clickUrl).concat(".apk");
                File file = new File(BaseApplication.getBaseApplication().getCacheDir(), "apk");
                if (!file.exists()) {
                    file.mkdirs();
                }
                String path = new File(file, fileName).getAbsolutePath();
                if (!new File(path).exists()) {
                    try {
                        new File(path).createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                unkownADView.pointPost(DOWNLOAD, "winDownloadUrls APP下载", metaGroupDTO.winDownloadUrls);
                //下载
                unkownADView.download(url, file.getAbsolutePath(), fileName);
            }
        }
    }

    NotifyDownloadListener callBack = new NotifyDownloadListener() {

        @Override
        public void download(String url) {

        }
    };
    ProxyDownListener proxyDownListener;

    @Override
    public void onClick(View v) {
        if (baseUnkownAd == null) {
            return;
        }
        if (proxyDownListener == null) {
            proxyDownListener = new ProxyDownListener(this);
        }
        UnkownAdBean unkownAdBean = baseUnkownAd;
        if (unkownAdBean.metaGroup != null && unkownAdBean.metaGroup.size() > 0) {
            UnkownAdBean.MetaGroupDTO metaGroupDTO = unkownAdBean.metaGroup.get(0);
            if (metaGroupDTO != null) {
                click(metaGroupDTO.winCNoticeUrls);

                //interactionType=3
                //当前可以先忽略这个,目前返回的只有1和2
                if (metaGroupDTO.interactionType == 3) {//进入下载页面
                    Activity activity = (Activity) getContext();
                    Intent intent = new Intent(activity, WebActivty.class);
                    intent.putExtra("url", metaGroupDTO.clickUrl);
                    String key = Integer.toString(System.identityHashCode(proxyDownListener));
                    intent.putExtra("key", key);
                    UNKOWN.addListener(key, proxyDownListener);
                    activity.startActivity(intent);
                    InstallObsever.getInstance().register(metaGroupDTO.packageName, metaGroupDTO.winInstallEndUrls, this);

                } else if (metaGroupDTO.interactionType == 2) {//下载类
                    boolean isInstall = ApkUtils.isInstall(metaGroupDTO.packageName);
                    if (isInstall) {
                        openApp(metaGroupDTO);
                    } else {
                        String downUrl = metaGroupDTO.clickUrl;


                        InstallObsever.getInstance().register(metaGroupDTO.packageName, metaGroupDTO.winInstallEndUrls, this);


                        String key = MD5Util.getMD5(downUrl);
                        String path = SpManager.getString(key, "");
                        if (ApkUtils.checkApkFileIsVaild(path)) {
                            if (metaGroupDTO != null) {
                                pointPost(INSTALL, "winInstallUrls APP安装", metaGroupDTO.winInstallUrls);
                            }
                            ApkUtils.installApk(BaseApplication.getBaseApplication(), path);
                        } else {
                            String fileName = MD5Util.getMD5(metaGroupDTO.clickUrl).concat(".apk");
                            File file = new File(BaseApplication.getBaseApplication().getCacheDir(), "apk");
                            if (!file.exists()) {
                                file.mkdirs();
                            }
                            path = new File(file, fileName).getAbsolutePath();
                            if (!new File(path).exists()) {
                                try {
                                    new File(path).createNewFile();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            pointPost(DOWNLOAD, "winDownloadUrls APP下载", metaGroupDTO.winDownloadUrls);
                            //下载
                            download(metaGroupDTO.clickUrl, file.getAbsolutePath(), fileName);
                        }
                    }
                } else if (metaGroupDTO.interactionType == 1) {//跳转类
                    Activity activity = (Activity) getContext();
                    Intent intent = new Intent(activity, WebActivty.class);
                    intent.putExtra("url", metaGroupDTO.clickUrl);
                    String key = Integer.toString(System.identityHashCode(proxyDownListener));
                    intent.putExtra("key", key);
                    UNKOWN.addListener(key, proxyDownListener);
                    activity.startActivity(intent);
                }
            }
        }
    }

    private void openApp(UnkownAdBean.MetaGroupDTO metaGroupDTO) {
        if (metaGroupDTO.deepLink) {
            try {
                pointPost(DEEP_LINK, "winDeepLinkUrls deeplink广告尝试唤起app", metaGroupDTO.winDeepLinkUrls);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(metaGroupDTO.deepLinkUrl));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                BaseApplication.getBaseApplication().startActivity(intent);
                pointPost(DEEP_LINK, "winDeepLinkSuccessUrls deeplink唤起成功", metaGroupDTO.winDeepLinkSuccessUrls);
            } catch (Exception exception) {

                try {
                    Intent intent = BaseApplication.getBaseApplication().getPackageManager().getLaunchIntentForPackage(metaGroupDTO.packageName);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    BaseApplication.getBaseApplication().startActivity(intent);
                } catch (Exception exception1) {
                    pointPost(DEEP_LINK, "winDeepLinkFailUrls deeplink唤起失败", metaGroupDTO.winDeepLinkFailUrls);
                }
            }
        } else {
            try {
                Intent intent = BaseApplication.getBaseApplication().getPackageManager().getLaunchIntentForPackage(metaGroupDTO.packageName);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                BaseApplication.getBaseApplication().startActivity(intent);
                pointPost(INSTALL_OPEN, "winInstallOpenUrls APP安装后打开", metaGroupDTO.winInstallOpenUrls);

            } catch (Exception exception1) {

            }
        }
    }


    public void show() {

    }

    private static class ProxyDownloadlistener implements DownloadUtil.OnDownloadListener {

        SoftReference<UnkownADView> unkownADViewSoftReference;

        ProxyDownloadlistener(UnkownADView unkownADView) {
            unkownADViewSoftReference = new SoftReference<>(unkownADView);
        }

        @Override
        public void onDownloadSuccess(String url, final File file) {
            if (unkownADViewSoftReference.get() != null) {
                UnkownADView unkownADView = unkownADViewSoftReference.get();

                if (ApkUtils.checkApkFileIsVaild(file.getAbsolutePath())) {
                    String key = MD5Util.getMD5(url);
                    SpManager.save(key, file.getAbsolutePath());
                    unkownADView.downloadSucc(url, file);
                    UnkownAdBean.MetaGroupDTO metaGroupDTO = unkownADView.getMetaGroupDTOBean();
                    if (metaGroupDTO != null) {
                        unkownADView.pointPost(DOWNLOAD, "winDownloadEndUrls  APP 下载完成", metaGroupDTO.winDownloadEndUrls);
                        unkownADView.pointPost(INSTALL, "winInstallUrls  APP安装", metaGroupDTO.winInstallUrls);
                    }

                    ApkUtils.installApk(unkownADView.getContext(), file.getAbsolutePath());

                }


            }

        }

        @Override
        public void onDownloading(String url, int progress) {
            Log.e("onDownloading", "progress=" + progress);
            if (unkownADViewSoftReference.get() != null) {
                UnkownADView unkownADView = unkownADViewSoftReference.get();
                if (unkownADView != null) {
                    unkownADView.downloadProgress(url, progress);
                }
            }

        }

        @Override
        public void onDownloadFailed(String url, Exception e) {
            if (unkownADViewSoftReference.get() != null) {
                UnkownADView unkownADView = unkownADViewSoftReference.get();
                if (unkownADView != null) {
                    unkownADView.downloadErr(url, e);
                }
            }

        }
    }

    DownloadUtil.OnDownloadListener downloadListener;

    protected void download(String downUrl, String path, String fileName) {
        if (downloadListener == null) {
            downloadListener = new ProxyDownloadlistener(this);
        }
        DownloadUtil.get().download(downUrl, path, fileName, downloadListener);
    }

    abstract void downloadProgress(String url, int progress);

    abstract void downloadSucc(String url, File progress);

    abstract void downloadErr(String url, Exception e);


    public static final int CLICK = 1, ADCLOSE = 2, REWARD = 3, SKIP = 4, EXPOSURE = 5, PLAY_VIDEO = 6, DEEP_LINK = 7, INSTALL = 8, DOWNLOAD = 9, INSTALL_OPEN = 10;


    public void adClose() {
        if (adCallBack != null && adCallBack instanceof IClose) {
            ((IClose) adCallBack).close();
        }
        pointPost(REWARD, "激励视频 关闭", null);
    }

    public void reward() {
        UnkownAdBean.MetaGroupDTO metaGroupDTO = getMetaGroupDTOBean();
        if (metaGroupDTO != null) {
            pointPost(REWARD, "激励视频 播放完成", metaGroupDTO.winCompleteUrls);
        }

        if (adCallBack != null) {
            ((IReward) adCallBack).reward();
        }
    }

    public void click(List<String> winCNoticeUrls) {
        if (adCallBack != null) {
            ((IClick) adCallBack).click();
        }
        pointPost(CLICK, "winCNoticeUrls  广告点击", winCNoticeUrls);
    }

    public void skip() {
        UnkownAdBean.MetaGroupDTO metaGroupDTO = getMetaGroupDTOBean();
        if (metaGroupDTO != null) {
            pointPost(SKIP, "广告跳过", getMetaGroupDTOBean().winIgnoreUrls);
        }

        if (adCallBack != null) {
            ((ISkip) adCallBack).skip();
        }
    }

    public void exposure(List<String> winNoticeUrls) {
        UI.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (adCallBack != null) {
                    ((IExposure) adCallBack).exposure();
                }
                pointPost(EXPOSURE, "winNoticeUrls   广告展现曝光", winNoticeUrls);
            }
        },1000);

    }

    public void adTick(int i) {
        if (adCallBack != null) {
            ((IADTick) adCallBack).onADTick(i);
        }
    }

    public void err() {
        if (adCallBack != null) {
            adCallBack.err();
        }
    }


    public void pointPost(int action, String key, List<String> winloadUrls) {
        LogUtils.showLog(TAG, key );
        if (winloadUrls != null)
            for (int i = 0; i < winloadUrls.size(); i++) {
                String url = winloadUrls.get(i);
                String uu = replaceUrl(action, url);
                winloadUrls.set(i, uu);
            }


        if (winloadUrls != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    for (int i = 0; i < winloadUrls.size(); i++) {
                        String url=winloadUrls.get(i);
                        LogUtils.showLog(TAG, key +"   "+url);
                        OkHttpUtil.getInstance().getResult(url);
                    }
                }
            }).start();


        }
    }

    float downX = 0;
    float downY = 0;
    float upX = 0;
    float upY = 0;


    private static class ACTION {
        int action;
        long time;
        float downX = 0;
        float downY = 0;
        float upX = 0;
        float upY = 0;
    }

    String lastUUID;
    ACTION actionBean;

    int lastACTION = -1;

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            downX = event.getX();
            downY = event.getY();
            actionBean = new ACTION();
            actionBean.downX = downX;
            actionBean.downY = downY;
            Log.e("onTouchEvent", "dispatchTouchEvent ACTION_DOWN");
        } else if (action == MotionEvent.ACTION_UP) {
            upX = event.getX();
            upY = event.getY();
            if (lastACTION == MotionEvent.ACTION_DOWN || lastACTION == MotionEvent.ACTION_MOVE) {
                actionBean.upX = upX;
                actionBean.upY = upY;
                if (Math.abs(downX - upX) <20 && Math.abs(downY - upY) < 20) {
                    actionBean.time = System.currentTimeMillis();
                    actionBean.action = CLICK;
                }
            }
            Log.e("onTouchEvent", "dispatchTouchEvent ACTION_UP");
        }
        lastACTION = action;
        return super.dispatchTouchEvent(event);
    }

    private String replaceUrl(int action, String url) {
        int[] xy = new int[2];
        getLocationInWindow(xy);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        url = url.replace("__WIDTH__", Integer.toString(width))
                .replace("__HEIGHT__", Integer.toString(height))
                .replace("__T_TS__", Long.toString(System.currentTimeMillis() / 1000));

//        CLICK = 1, ADCLOSE = 2, REWARD = 3, SKIP = 4, EXPOSURE = 5, PLAY_VIDEO = 6, DEEP_LINK = 7, INSTALL = 8, DOWNLOAD = 9, INSTALL_OPEN = 10;
        if (action == REWARD || action == SKIP || EXPOSURE == action || PLAY_VIDEO == action || DEEP_LINK == action) {
            url = url.replace("__EVENT_TIME_START__", Long.toString(System.currentTimeMillis() - (new Random().nextInt(500) + 10)))
                    .replace("__EVENT_TIME_END__", Long.toString(System.currentTimeMillis()));
        } else if (INSTALL_OPEN == action) {
            url = url.replace("__EVENT_TIME_START__", Long.toString(System.currentTimeMillis() - (new Random().nextInt(2500) + 10)))
                    .replace("__EVENT_TIME_END__", Long.toString(System.currentTimeMillis()));
        } else if (PLAY_VIDEO == action || action == INSTALL || action == DOWNLOAD) {
            url = url.replace("__EVENT_TIME_START__", Long.toString(System.currentTimeMillis() - (new Random().nextInt(100) + 10)))
                    .replace("__EVENT_TIME_END__", Long.toString(System.currentTimeMillis()));
        }


        if (action == CLICK) {
            url = url.replace("__DOWN_X__", Integer.toString((int)actionBean.downX))
                    .replace("__DOWN_Y__", Integer.toString((int)actionBean.downY))
                    .replace("__UP_X__", Integer.toString((int)actionBean.upX))
                    .replace("__UP_Y__", Integer.toString((int)actionBean.upY))
                    .replace("__DP_WIDTH__", Integer.toString(UNKOWN.pxToDp(width)))
                    .replace("__DP_HEIGHT__", Integer.toString(UNKOWN.pxToDp(height)))
                    .replace("__DP_DOWN_X__", Integer.toString(UNKOWN.pxToDp((int) actionBean.downX)))
                    .replace("__DP_DOWN_Y__", Integer.toString(UNKOWN.pxToDp((int) actionBean.downY)))
                    .replace("__DP_UP_X__", Integer.toString(UNKOWN.pxToDp((int) actionBean.upX)))
                    .replace("__DP_UP_Y__", Integer.toString(UNKOWN.pxToDp((int) actionBean.upY)))
                    .replace("__EVENT_TIME_START__", Long.toString(actionBean.time))
                    .replace("__EVENT_TIME_END__", Long.toString(System.currentTimeMillis()))
                    .replace("__SLD__", "0");//广告交互方式
        }
        double lat = Double.parseDouble(SpManager.getString(k.lat, "0.0"));
        double lon = Double.parseDouble(SpManager.getString(k.lng, "0.0"));

        if (lat == 100 || lon == 100) {
            lat = lon = 0;
        }
        if (lat != 0) {
            url = url.replace("__LATITUDE__", Double.toString(lat))
                    .replace("__LONGITUDE__", Double.toString(lon));
        }
        return url;
    }


}
